package cn.tedu.cs.filter;

import cn.tedu.cs.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*urlPatterns配置过滤器处理的资源路径*/
@WebFilter(filterName = "MyFilter",urlPatterns = {"/insertProduct.html","/insertBanner.html","/admin.html"})
public class MyFilter implements Filter {
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //因为要使用子类型中的方法，所以需要将父类类型强转成子类类型
        HttpServletRequest ht=(HttpServletRequest)req;
        HttpServletResponse hs=(HttpServletResponse) resp;
        //从请求对象在得到Session 再从Session中得到User
        User user=(User)ht.getSession().getAttribute("user");
        if(user==null){//代表没登录
            //没登录则重定向到登录页面
            hs.sendRedirect("/login.html");
        }else {//代表登录了
            chain.doFilter(req,resp);
        }


        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
